<template>
  <div class="search-container">
    <!-- 搜索栏》事件监听 -->
    <form action="/">
      <van-search
        background="#1989fa"
        v-model="value"
        show-action
        placeholder="请输入搜索关键词"
        @cancel="onCancel"
        @search="onSearch"
        @focus="isShowResult = false"
      >
        <template #action>
          <div @click="onSearch(value)">搜索</div>
        </template>
      </van-search>
    </form>

    <search-result
      :searchText="value"
      v-if="isShowResult"
    />

    <search-suggestion
      v-else-if="value"
      :searchText="value"
      @search="onSearch"
    />

    <search-history
      v-else
      :historyList="historyList"
      @search="onSearch"
      @clearAll="historyList = []"
    />
  </div>
</template>

<script>
import SearchHistory from './components/search-history.vue'
import SearchResult from './components/search-result.vue'
import SearchSuggestion from './components/search-suggestion.vue'
import {setLocal, getLocal} from '@/utils/storage.js'

export default {
  data () {
    return {
      value: '',
      isShowResult: false,
      historyList: getLocal('historyList')[0] ? getLocal('historyList') : []
    }
  },
  components: {
    SearchResult,
    SearchHistory,
    SearchSuggestion
  },
  methods: {
    onSearch (val) {
      this.value = val

      // 如果数组已经存在这个数据 则需要先把之前存的数据 删除掉
      let index = this.historyList.indexOf(val)
      if(index !== -1) {
        this.historyList.splice(index, 1)
      }

      // 任何情况 都需呀把最新搜索的 内容 从前插入进来
      this.historyList.unshift(val)

      this.isShowResult = true
    },
    onCancel () {
      this.$toast('取消')

      this.isShowResult = false
    }
  },
  watch: {
    historyList(newVal) {
      setLocal('historyList', newVal)
    }
  }
}
</script>

<style scoped lang='less'>
.search-container {
  padding-top: 108px;
  .van-search{
    position: fixed;
    top: 0;
    left: 0;
    z-index: 999;
    width: 100%;
  }

  .van-search__action {
    color: #fff;
  }
  .van-search__action:active {
    background-color: #1989fa;
  }
}

</style>
